package com.epfresh.fragment;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.epfresh.R;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.activity.WebCommonActivity;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.JsBridgeValue;
import com.epfresh.constant.Constant;
import com.google.gson.GsonBuilder;

import java.io.File;
import java.util.Map;

import com.epfresh.api.utils.*;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseApplication;

@SuppressLint("ValidFragment")
public class WebFragment extends Fragment {
    private PtrFrameLayout ptrFrameLayout;
    WebView webview;
    String url;
    String storeId;
    private ProgressBar pb;
    public static final String URL_KEY = "url_key";

    PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {

            if (webview != null) {

                return /*PtrDefaultHandler.checkContentCanBePulledDown(frame, webview, header)*/false;
            }
            return false;
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {

            if (webview != null && url != null && !"".equals(url)) {
                webview.loadUrl(url);
            } else {
            }
            ptrFrameLayout.refreshComplete();

        }
    };

    public WebFragment() {
    }

    public WebFragment(String url, String storeId) {
        this.url = url;
        this.storeId = storeId;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_webview, container, false);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ptrFrameLayout = (PtrFrameLayout) view.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
        webview = (WebView) view.findViewById(R.id.wv);
        pb = (ProgressBar) view.findViewById(R.id.pb);
        pb.setVisibility(View.VISIBLE);
        webViewSetting();
        webview.loadUrl(url);
    }

/*
    public void webViewSetting() {
        android.webkit.WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互

//        settings.setAppCachePath(cacheDirPath); //设置缓存的指定路径
        settings.setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(android.webkit.WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 99) {
                    pb.setVisibility(View.GONE);
                } else {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);
                    pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
            }
        });
        webview.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                view.loadUrl(url);
//
//                return true;
//            }


            @Override
            public void onLoadResource(WebView view, String url) {

            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }
        });

        webview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }*/

    public void webViewSetting() {
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互
//        settings.setAppCachePath(cacheDirPath); //设置缓存的指定路径
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.addJavascriptInterface(new JsBridge(), "JSBridge");
/*        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);*/
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setAllowFileAccess(true);
        settings.setLoadWithOverviewMode(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setUserAgentString(null);
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setUseWideViewPort(true);
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 99) {
                    pb.setVisibility(View.GONE);
                } else {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);
                    pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            private View myView = null;
            private CustomViewCallback myCallback = null;

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                if (myCallback != null) {
                    myCallback.onCustomViewHidden();
                    myCallback = null;
                    return;
                }
                ViewGroup parent = (ViewGroup) webview.getParent();
                parent.removeView(webview);
                parent.addView(view);
                myView = view;
                myCallback = callback;
                getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }

            public void onHideCustomView() {
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                if (myView != null) {

                    if (myCallback != null) {
                        myCallback.onCustomViewHidden();
                        myCallback = null;
                    }

                    ViewGroup parent = (ViewGroup) myView.getParent();
                    parent.removeView(myView);
                    parent.addView(webview);
                    myView = null;
                }

                final WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
                attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getActivity().getWindow().setAttributes(attrs);
                getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
        });
    }


    /*openVideoLibrary 本地视频 takeVideo 选择视频 upload 上传 takePhoto 拍照 openAlbum 相册 loginData 登录信息 deviceInfo 设备信息 appCallBack 返回* */
    private Handler mHandler = new Handler();
    String h5Key = "";

    public class JsBridge {
        @JavascriptInterface
        public void callHandler(String functionName, String value, final String param3) {
            Log.e("functionName:", functionName + "-" + value + "-" + param3);
            h5Key = param3;
            if ("loginData".equals(functionName)) {
                final Map map = new ArrayMap();
                map.put("clientIdentifierCode", BaseApplication.getInstance().getClientIdentifierCode());
                map.put("token", BaseApplication.getInstance().getUser().getAccess_token());
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }
            if ("deviceInfo".equals(functionName)) {
                final Map map = new ArrayMap();
                map.put("os", "android");
                map.put("osVersion", Build.VERSION.RELEASE);
                map.put("model", Build.MODEL);
                map.put("net", IntenetUtil.getNetworkState(getContext()));
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }
            if ("getStoreInfo".equals(functionName)) {//todo: 采购端哪儿来的店铺信息？？？
                final Map map = new ArrayMap();
/*                map.put("storeType", ApplicationHelper.getInstance().getMerchant().getStoreCategoryType());
                map.put("storeName", ApplicationHelper.getInstance().getStoreName());*/
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }

            if ("appCallBack".equals(functionName)) {//返回结束
                if (webview.canGoBack())
                    webview.goBack();
                //getActivity().finish();
            }

            if ("commodityDetail".equals(functionName)) {//商品详情 todo:新要求参数storeId
                JsBridgeValue jsBridgeValue = JsonUtils.fromJson(value, JsBridgeValue.class);
                if (jsBridgeValue != null)
                    intoProductDetail(jsBridgeValue.getProductId(), jsBridgeValue.getPromotionItemId());

            }

            if ("openLink".equals(functionName) || "openList".equals(functionName)) {//返回结束
                //value:{"link":"https://www.baidu.com","title":"百度好吃的粉"}

                JsBridgeValue jsBridgeValue = JsonUtils.fromJson(value, JsBridgeValue.class);
                if (jsBridgeValue != null){
                    intoWebDetail(jsBridgeValue.getLink(),jsBridgeValue.getTitle());
                }
            }


        }
    }


    void intoWebDetail(String url, String title) {
        if (url == null || "".equals(url)) {
            return;
        }
        Intent intent = new Intent(getContext(), WebCommonActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, url);
        intent.putExtra(Constant.KEY_WEB_TITLE, title);
        startActivity(intent);
    }

    void intoProductDetail(String productId, String promotionItemId) {
        if (productId == null || "".equals(productId)) {
            return;
        }
        Intent intent = new Intent(getContext(), DetailGoodsActivity.class);

        intent.putExtra("id", productId + "");
        intent.putExtra("promotionItemId", promotionItemId);
        startActivity(intent);
    }

    @TargetApi(19)
    void evaluateJs(final String value) {
        Log.e("javascript", value.toString());
        final int version = Build.VERSION.SDK_INT;// 因为该方法在 Android 4.4 版本才可使用，所以使用时需进行版本判断
        if (version < 18) {
            webview.loadUrl(value);
        } else {
            webview.evaluateJavascript(value, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        }
    }


}
